﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utils
{
    public static partial class ExtensionHelper
    {
        #region IpToLong IP 转换为 long
        /// <summary>
        /// IP 转换为 long
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static long IpToLong(this string ip)
        {
            char[] separator = new char[] { '.' };
            string[] items = ip.Split(separator);

            return long.Parse(items[0]) << 24

                    | long.Parse(items[1]) << 16

                    | long.Parse(items[2]) << 8

                    | long.Parse(items[3]);
        }
        #endregion

        #region LongToIP 数字转换为IP
        /// <summary>
        /// 数字转换为IP
        /// </summary>
        /// <param name="ipInt"></param>
        /// <returns></returns>
        public static string LongToIP(this long ipInt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append((ipInt >> 24) & 0xFF).Append(".");
            sb.Append((ipInt >> 16) & 0xFF).Append(".");
            sb.Append((ipInt >> 8) & 0xFF).Append(".");
            sb.Append(ipInt & 0xFF);
            return sb.ToString();
        }
        #endregion
    }
}
